package org.obsidianrad.utils.obsobserver;


import java.util.ArrayList;
import java.util.List;

import org.obsidianrad.server.services.ObsModel;
import org.obsidianrad.server.services.obj2db.commodities.PagingLoadResult;
import org.obsidianrad.utils.Constant.ObsidianOperations;
import org.springframework.beans.factory.InitializingBean;


/**
 * 
 * @author eliosh
 * @version $Rev$
 * @lastautorcommit $Author$
 * @lastdatecommit $Date$
 */
public abstract class AbstractObsidianSubjectAndObserver implements ObsSubject, ObsObserver, InitializingBean {

	private List<ObsObserver> observers;
	private List<ObsSubject> observed;
	
	public AbstractObsidianSubjectAndObserver(){
		observers = new ArrayList<ObsObserver>();
		observed = new ArrayList<ObsSubject>();
	}
	
	@Override
	public final void addObsObserver(ObsObserver observer) {
		observers.add(observer);
	} 

	@Override
	public void removeObsObserver(ObsObserver observer) {
		if(observers != null){
			observers.remove(observer);
		}
	}
	
	public List<ObsSubject> getObserved() {
		return observed;
	}

	public void setObserved(List<ObsSubject> observed) {
		this.observed = observed;
	}

	@SuppressWarnings("unchecked")
	@Override
	public final void obs_notify(Object obj, ObsidianOperations op) {
		if(observers==null){
			return;
		} else if (observers.size()==0){
			return;
		}
		switch (op) {
//			case KEY_DELETE_MANY:
//				for(ObsObserver obs: observers){
//					obs.notifyDeleteMany(obj);
//				}
//				break;
			case KEY_DELETE_ONE:
				for(ObsObserver obs: observers){
					obs.notifyDeleteOne((ObsModel)obj);
				}
				break;
			case KEY_GET_SINGLE:
				for(ObsObserver obs: observers){
					obs.notifyGetSingle((ObsModel)obj);
				}
				break;
			case KEY_GET_LIST_FILTERED:
				for(ObsObserver obs: observers){
					obs.notifyGetListFiltered((PagingLoadResult<ObsModel>)obj);
				}
				break;
			case KEY_GET_LIST:
				for(ObsObserver obs: observers){
					obs.notifyGetList((PagingLoadResult<ObsModel>)obj);
				}
				break;
			case KEY_SAVE:
				for(ObsObserver obs: observers){
					obs.notifySave((ObsModel)obj);
				}
				break;
			case KEY_UPDATE_ONE:
				for(ObsObserver obs: observers){
					obs.notifyUpdateOne((ObsModel)obj);
				}
				break;
//			case KEY_UPDATE_MANY:
//				for(ObsObserver obs: observers){
//					obs.notifyUpdateMany((PagingLoadResult<ObsModel>)obj);
//				}
//				break;
		}
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		if( (observed!=null) && (observed.size()>0) ){
			for(ObsSubject subject: observed){
				subject.addObsObserver(this);
			}
		}		
	}

	@Override
	public void notifyDeleteOne(ObsModel obj) {}

	@Override
	public void notifyGetList(PagingLoadResult<ObsModel> obj) {}

	@Override
	public void notifyGetListFiltered(PagingLoadResult<ObsModel> obj) {}

	@Override
	public void notifyGetSingle(ObsModel obj) {}

	@Override
	public void notifySave(ObsModel obj) {}

	@Override
	public void notifyUpdateOne(ObsModel obj) {}

}
